<?php
/***
*
* Class: DropdownController //下拉框数据
* Author: Jason ZHENG
* Data: 2018-06-21
*
***/
namespace App\Http\Controllers;

use App\Service\DataReturnService as DRS;
use Illuminate\Support\Facades\DB;

class DropdownController extends Controller
{
    /**
     * 实例化一个新的控制器实例。
     *
     * @return void
     */
    public function __construct()
    {
        
    }

    public function index()
    {
    	return "Dropdown controller";
    }

    public function address()
    {
        $level1Query =  Db::table('address')->where(['levelType'=>1])->get()->toArray();
        $level2Query =  Db::table('address')->where(['levelType'=>2])->get()->toArray();
        $level3Query =  Db::table('address')->where(['levelType'=>3])->get()->toArray();

        $level1 = array_map('get_object_vars', $level1Query);
        $level2 = array_map('get_object_vars', $level2Query);
        $level3 = array_map('get_object_vars', $level3Query);

        $provinces = [];
        foreach ($level1 as $k => $p) {
            $province = (array)$p;
            $provinces[$k]['province'] = ['value' => $province['ID'], 'label' => $province['Name'] ];
            $cities = array_values(array_filter($level2, function($city) use($province) {return $city['ParentId'] == $province['ID']; } ) );
            
            $cities = array_map(function($c){return ['value'=>$c['ID'], 'label'=>$c['Name'] ];}, $cities);

            $provinces[$k]['province'] = array_merge($provinces[$k]['province'], ['children' => $cities]);
            foreach ($provinces[$k]['province']['children'] as $j => $city)
            {
                $towns = array_values(array_filter($level3, function($town) use($city) {return $town['ParentId'] == $city['value']; } ) );
                $towns = array_map(function($t){return ['value'=>$t['ID'], 'label'=>$t['Name'] ];}, $towns);
                $provinces[$k]['province']['children'][$j]['children'] = $towns;
            }

        }

        return DRS::returnOk($provinces,'全国各省市区列表');
    }

}